package cn.jtfadmin.base.data.jpa.utils;

import cn.jtfadmin.base.lang.config.ApplicationHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.concurrent.Callable;

/**
 * 事物工具
 */
public class TxUtils {

    /**
     * 在新事物内执行
     * @param callable
     * @param <T>
     * @return
     */
    public static  <T> T execute(Callable<T> callable){
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        PlatformTransactionManager bean = ApplicationHolder.getApplicationContext().getBean(PlatformTransactionManager.class);
        TransactionStatus transaction = bean.getTransaction(def);
        try {
            T call = callable.call();
            bean.commit(transaction);
            return call;
        } catch (Exception ex) {
            bean.rollback(transaction);
            throw new RuntimeException(ex);
        }
    }
}
